package com.qf.controller;

import com.qf.util.UploadUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/*
杨威
2021/9/18
19:14
*/
@WebServlet("/downLoad")
public class DownLoadController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uuidFileName = request.getParameter("uuidFileName");
        String fileName = uuidFileName.substring(uuidFileName.indexOf("_") + 1);

        String filePath = request.getServletContext().getRealPath("/WEB-INF/upload");
        String newFilePath = UploadUtil.creatNewFilePath(filePath, fileName);

        response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));

        FileInputStream fis=new FileInputStream(newFilePath+File.separator+uuidFileName);
        ServletOutputStream outputStream = response.getOutputStream();

        int i=-1;
        while((i=fis.read())!=-1){
            outputStream.write(i);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
